package br.ufal.ic.fracao.agent.resolution.operation.simplification;

import java.io.IOException;

import org.jdom.JDOMException;

import br.ufal.ic.fracao.especialist.domain.Item;
import br.ufal.ic.fracao.especialist.inference.InferenceAlgorithm;

public class SimplificationAdapter {
	
	public String getSolution(int n1, int d1) throws IOException, JDOMException{
		InferenceAlgorithm algorithm = new InferenceAlgorithm();
				        
        Item fato1 = new Item();
        fato1.setDescription("Simplification");
        fato1.setValue(String.valueOf(true));
        fato1.setCertaintyFactor(0.2);
        algorithm.addToMemoryWorking(fato1);
        
        Item conclusion1 = new Item("(n1/mdc)/(d1/mdc)", "true");
        String result1 = algorithm.doForwardChaining(conclusion1, false);
                
        if (result1.equalsIgnoreCase("(n1/mdc)/(d1/mdc)")) {
        	int mdc = this.mdc(n1, d1);
        	int numerator = n1/mdc;
        	int denominator = d1/mdc;
        	if(denominator == 1){
        		return String.valueOf(numerator);
        	}else{
        		return numerator + "/" + denominator;
        	}
        }
		return null;
	}
	
	public int mdc(int m, int n){
		int x = m;
		int y = n;
		int resto = x % y;
		while(resto != 0){
			x = y;
			y = resto;
			resto = x % y;
			
		}
		return y;
	}
}
